package app.sevenc.lib_framework.mvvm.v

import android.os.Bundle
import androidx.core.util.forEach
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import app.sevenc.lib_framework.ktx.getVmClazz
import app.sevenc.lib_framework.mvvm.vm.BaseFrameViewModel
import java.lang.reflect.ParameterizedType

/**
 * Mvvm设计模式 Activity基类
 *
 * @author Seven-C
 * @date 2021/8/25
 */
abstract class BaseFrameMvvmActivity<VM : BaseFrameViewModel> : BaseFrameActivity() {

    private lateinit var mBinding: ViewDataBinding
    val mViewModel: VM by lazy { createViewModel() }

    /**
     * 创建viewModel
     * type.actualTypeArguments[0]=BaseFrameViewModel
     * val type = javaClass.genericSuperclass as ParameterizedType
     * val vmClass = type.actualTypeArguments[0] as Class<VM>
     *
     */
    private fun createViewModel(): VM {
        return mActivityProvider.get(getVmClazz(this, 0))
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        initDataBinding()
    }

    /**
     * 初始化 mBinding
     * 绑定 layoutId 和 ViewModel 还有其他的变量
     */
    private fun initDataBinding() {
        val dataBindingConfig = getDataBindingConfig()
        mBinding = DataBindingUtil.setContentView(this, dataBindingConfig.layoutId)
        mBinding.lifecycleOwner = this
        mBinding.setVariable(dataBindingConfig.vmVariableId, mViewModel)
        dataBindingConfig.bindingParams.forEach { i: Int, any: Any ->
            mBinding.setVariable(i, any)
        }
    }
}